package com.example.utils;

import jakarta.servlet.http.HttpServletRequest;

/**
 * IP工具类
 *
 * @auth shanyue
 * @date 2025年08月06日12:26
 */
public class IpUtils {

    /**
     * 获取客户端真实IP地址
     *
     * @param request 请求对象
     * @return 客户端真实IP字符串
     */
    public static String getClientIp(HttpServletRequest request) {
        String[] headerNames = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP"
        };
        for (String header : headerNames) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                // 如果包含多个IP，取第一个
                if (ip.contains(",")) {
                    ip = ip.split(",")[0].trim();
                }
                return ip;
            }
        }
        // 以上请求头都没有，则用请求的远程地址
        return request.getRemoteAddr();
    }
}
